package liujinliang.natappvip.cc.portrait;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.VoiceInteractor;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.annotation.DrawableRes;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class MainActivity extends AppCompatActivity {

    private static final int CHOOSE_PHOTO = 2;

    private static final int PHOTO_REQUEST_CUT = 3;

    /** 头像显示 */
    private ImageView pictureF;

    /** 头像Bitmap */
    private Bitmap head;

    /** 图片存储路径 */
    private String path;

    Uri uritempFile;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 初始化ImageView
        pictureF = (ImageView) findViewById(R.id.picture_f);

        // 初始化Button
        Button chooseBtn = (Button) findViewById(R.id.choose_from_album);

        // 初始化点击事件
        chooseBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                // 权限检查
                if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {

                    // 申请权限
                    ActivityCompat.requestPermissions(MainActivity.this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
                } else {

                    // 打开相册
                    openAlbum();
                }

            }
        });
    }

    private void openAlbum() {

        // 创建动作 + 创建动作的数据结构
        Intent intent = new Intent("android.intent.action.GET_CONTENT");
        intent.setType("image/**");

        // startActivity
        startActivityForResult(intent, CHOOSE_PHOTO);
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case CHOOSE_PHOTO:
                if (resultCode == RESULT_OK) {
                    // 裁剪图片
                    cropPhoto(data.getData());
                    // 判断手机系统系统版本号
//                    if (Build.VERSION.SDK_INT >= 19) {
//                        // 4.4 以上用这个方法处理图片
//                        handleImageOnKitKat(data);
//                    } else {
//                        // 4.4 以下用这个方法处理图片
//                        handleImageBeforKitKat(data);
//                    }
                }
                break;
            case PHOTO_REQUEST_CUT:
                try {

                    //将Uri图片转换为Bitmap
                    Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uritempFile));

                    Log.i("Gene", uritempFile.toString());

                    // 显示图片
                    pictureF.setImageBitmap(bitmap);

                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                break;
        }
    }

    @TargetApi(19)
    private void handleImageOnKitKat(Intent data) {
//        String imagePath = null;
        Uri uri = data.getData();

//        if (DocumentsContract.isDocumentUri(this, uri)) {
//            Log.i("Gene", "1");
//            // 如果是document类型的Uri，则通过documentId进行处理
//            String id = DocumentsContract.getDocumentId(uri);
//            String selection = MediaStore.Images.Media._ID + "=" + id;
//            imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
//        } else if ("content".equalsIgnoreCase(uri.getScheme())) {
//            Log.i("Gene", "2");
//            // 如果是content类型的Uri，则使用普通方式处理
//            imagePath = getImagePath(uri, null);
//        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
//            Log.i("Gene", "3");
//            // 如果是file类型的图片，直接获取图片路径即可
//            imagePath = uri.getPath();
//        }
//
//        // 获取当前图片的存储路径
//        path = imagePath;
//
//        Log.i("Gene", path);

        // 裁剪图片
        cropPhoto(uri);
    }

    /**
     * 裁剪图片
     * @param uri
     */
    private void cropPhoto(Uri uri) {

        Intent intent = new Intent("com.android.camera.action.CROP");

        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 150);
        intent.putExtra("outputY", 150);
        intent.putExtra("return-data", true);

        //裁剪后的图片Uri路径，uritempFile为Uri类变量
        uritempFile = Uri.parse("file://" + "/" + Environment.getExternalStorageDirectory().getPath() + "/" + "sffddsssdadf" +".jpg");
        //Log.i("Gene", getAbsoluteImagePath(uritempFile));
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uritempFile);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());

        startActivityForResult(intent, PHOTO_REQUEST_CUT);

    }

//    private void handleImageBeforKitKat(Intent data) {
//        Uri uri = data.getData();
//        String imagePath = getImagePath(uri, null);
//        displayImage(imagePath);
//    }

    private void displayImage(String imagePath) {

        if (imagePath != null) {
            BitmapFactory.Options op3 = new BitmapFactory.Options();
            op3.inPreferredConfig = Bitmap.Config.ARGB_8888;
            Bitmap bm3 = BitmapFactory.decodeFile(imagePath, op3);
            pictureF.setImageBitmap(bm3);
        } else {
            Toast.makeText(this, "failed to get image", Toast.LENGTH_SHORT).show();
        }
    }

    private String getImagePath(Uri uri, String selection) {

        String path = null;

        // 通过Uri和selection获取真实的图片路径
        Cursor cursor = getContentResolver().query(uri, null, selection, null, null);

        if (cursor != null) {
            if (cursor.moveToFirst()) {
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }

    public String getAbsoluteImagePath(Uri contentUri)
    {
        String res = null;
        String[] proj = { MediaStore.Images.Media.DATA };
        Cursor cursor = getContentResolver().query(contentUri, proj, null, null, null);
        if (cursor.moveToFirst())
        {
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            res = cursor.getString(column_index);
        }
        cursor.close();
        return res;
    }

}
